package com.wj.wjaiagent.app;

import com.wj.wjaiagent.advisor.MyLoggerAdvisor;
import com.wj.wjaiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class JavaMasterApp {
    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "扮演深耕 Java 编程教育领域的专家。开场向用户表明身份，告知用户可倾诉 Java 学习过程中的各类难题。" +
            "围绕 Java 学习的三个阶段提问：零基础入门阶段询问核心概念理解、学习资源选择及编程思维建立的困扰；" +
            "有一定基础（进阶阶段）询问面向对象编程思想应用、集合框架与多线程等难点掌握、项目实战转化的问题；" +
            "有项目经验（实战阶段）询问代码性能优化、设计模式应用、框架（如 Spring/MyBatis）深入理解及大型项目架构设计的难题。" +
            "引导用户详述具体学习困境、已尝试的解决方法及希望达成的目标，以便给出专属的学习路径规划和问题解决方案。";



    /**
     * 初始化 ChatClient 客服端
     * @param dashscopeChatModel
     */
    public JavaMasterApp(ChatModel dashscopeChatModel) {
        // 初始化基于内存的对话记忆
        ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        // 自定义日志 Advisor ,可按需开启
                        new MyLoggerAdvisor()
                        // new ReReadingAdvisor()
                )
                .build();

    }

    /**
     * AI 基础对话 （支持多轮对话记忆）
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    public record LearnReport(String title, List<String> suggestions) {

    }
    /**
     * AI java学习报告功能 （实战结构化输出）
     * @param message
     * @param chatId
     * @return
     */
    public LearnReport doChatWithReport(String message, String chatId) {
        LearnReport learnReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成学习结果，标题为{用户名}的学习报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LearnReport.class);
        log.info("learnReport: {}", learnReport);
        return learnReport;
    }


    @Resource
    private VectorStore javaMasterVectorStore;
    @Resource
    private Advisor javaMasterAppRagCloudAdvisor;
    @Resource
    private VectorStore pgVectorVectorStore;
    @Resource
    private VectorStore javaMasterAppVectorStore;
    @Resource
    private QueryRewriter queryRewriter;

    /**
     * AI java学习知识库问答功能
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message, String chatId) {
        // 查询重写
        String rewrittenMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(rewrittenMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .advisors(new QuestionAnswerAdvisor(javaMasterAppVectorStore))   // 应用本地知识库问答（基于simpleVectorStore）
                //.advisors(javaMasterAppRagCloudAdvisor)    // 基于RAG检索增强服务（基于知识库服务）
                //.advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))   // 应用RAG检索增强服务（基于pgVectorStore）
                //.advisors(JavaMasterAppRagCustomAdvisorFactory.createJavaMasterAppRagCustomAdvisor(javaMasterVectorStore,"基础"))   // 应用自定义的RAG检索增强服务（文档搜索 + 上下文增强）
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    // java智习大师调用工具能力
    @Resource
    private ToolCallback[] allTools;

    /**
     *  java智习大师（支持调用工具）
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    public String doChatWithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     *  java智习大师（支持SEE流式传输）
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId) {
        return chatClient
                .prompt()
                .user(message)
                .advisors(sepc -> sepc.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY,10))
                .stream()
                .content();
    }



}
